package com.glory.brepda.activity.mfg;

import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.glory.brepda.R;
import com.glory.brepda.adapter.AddCarrierDataAdapter;
import com.glory.brepda.base.BaseActivity;
import com.glory.brepda.callback.CustomDialogEntityCallBack;
import com.glory.brepda.entity.EqpInfoEntity;
import com.glory.brepda.entity.response.BaseResponseBean;
import com.glory.brepda.utils.LotUtils;
import com.glory.brepda.utils.NetUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
import com.lzy.okgo.model.Response;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_DialogEntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_EntityCallBack;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_StaticMembers;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class EqpCombinationActivity extends BaseActivity {

    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.tvBaseSubmit)
    TextView tvBaseSubmit;
    @BindView(R.id.etEqpWorkID)
    FreeUI_ClearEditText etEqpWorkID;
    @BindView(R.id.etItemEqp)
    FreeUI_ClearEditText etItemEqp;
    @BindView(R.id.rvItemEqpList)
    RecyclerView rvItemEqpList;
    @BindView(R.id.llMain)
    LinearLayout llMain;
    private AddCarrierDataAdapter carrierAdapter;
    private String mMainObjectRRN = "";
    private List<EquipmentEntity> mItemList;
    private List<String> mItemEqpList;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_eqp_combination;
    }

    @Override
    protected void initView() {
        String title = getIntent().getStringExtra(FreeApi_StaticMembers.SHOW_PLUGIN_KEY);
        tvTitle.setText(title);
        tvBaseSubmit.setText("提交");
        initRecyclerView(rvItemEqpList,this);
        setMainLayout(llMain);
        carrierAdapter = getCarrierAdapter();
        rvItemEqpList.setAdapter(carrierAdapter);
        mItemList = new ArrayList<>();
        mItemEqpList = new ArrayList<>();

//        String ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"EQUIPMENT\":{\"UDF\":{\"RESERVED3\":\"\",\"RESERVED2\":\"\",\"RESERVED1\":\"GQP-F-409\",\"RESERVED7\":\"2020-12-12 14:14:58\",\"RESERVED6\":\"\",\"RESERVED10\":\"\",\"RESERVED5\":\"\",\"RESERVED4\":\"T1110\",\"RESERVED9\":\"\",\"FACAREA\":\"705\",\"RESERVED8\":\"\",\"INFACTORYTIME\":\"\"},\"OBJECTRRN\":94104598,\"EQUIPMENTID\":\"AE0393\",\"DESCRIPTION\":\"AE0393-TS-A06\",\"LOCATION\":\"TS-A06\",\"DEPARTMENT\":\"S区\",\"EQPTYPE\":\"F248\",\"STATUSMODELRRN\":1024702,\"EQPTYPEDETAIL\":\"SORTING\",\"EQPGROUP\":\"FT-160\",\"MODEL\":\"F248\",\"COMCLASS\":\"UP-Time\",\"STATE\":\"Productive-Time\",\"SUBSTATE\":\"RUN\",\"HOLDSTATE\":\"Off\",\"ISBATCH\":\"N\",\"ISMULTIPART\":\"N\",\"STYLE\":0,\"CREATED\":\"2020/04/27 09:07:00\",\"UPDATED\":\"2020/12/12 14:14:58\",\"UPDATEDBY\":\"admin\",\"CURRENTPARTNAME\":\"FS03801GD\",\"ISAVAILABLE\":true,\"ISBATCHLOTSIZECONTROL\":false},\"LISTEQUIPMENT\":[]}}}";
//        initEdit(etEqpWorkID, new editTextListener() {
//            @Override
//            public void onTextChangeListener(String s) {
//                BaseResponseBean<EqpInfoEntity> dd = (new Gson()).fromJson(ss, new TypeToken<BaseResponseBean<EqpInfoEntity>>() {
//                }.getType());
//                if (dd.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//                    mMainObjectRRN = dd.getResponse().getBody().getEQUIPMENT().getOBJECTRRN();
//                    if (mMainObjectRRN.equals("")){
//                        showToast("未获取到当前设备主键",false);
//                        etEqpWorkID.setText("");
//                        etEqpWorkID.requestFocus();
//                        return;
//                    }
//
//                    requestItemRRN(mMainObjectRRN);
//                }
//            }
//        });

        initEdit(etEqpWorkID, s -> LotUtils.searchEqpInfo(s, EqpCombinationActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
            @Override
            public void onSuccess(EqpInfoEntity response) {
                mMainObjectRRN = response.getEQUIPMENT().getOBJECTRRN();
                if (mMainObjectRRN.equals("")){
                    showToast("未获取到当前设备主键",false);
                    etEqpWorkID.setText("");
                    etEqpWorkID.requestFocus();
                    return;
                }

                requestItemRRN(mMainObjectRRN);
            }

            @Override
            public void onFail(Throwable t) {
                loadError(t,"EQPQUERY");
            }
        }));

//        String s1 = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"EQUIPMENT\":{\"UDF\":{\"RESERVED3\":\"\",\"RESERVED2\":\"12000359\",\"RESERVED1\":\"QP-F-008\",\"RESERVED7\":\"\",\"RESERVED6\":\"\",\"RESERVED10\":\"\",\"RESERVED5\":\"\",\"RESERVED4\":\"\",\"RESERVED9\":\"\",\"FACAREA\":\"\",\"RESERVED8\":\"\",\"INFACTORYTIME\":\"\"},\"OBJECTRRN\":94107116,\"EQUIPMENTID\":\"FT0008\",\"DESCRIPTION\":\"FT0008-TB115\",\"LOCATION\":\"TB115\",\"DEPARTMENT\":\"B区\",\"EQPTYPE\":\"C3D300\",\"STATUSMODELRRN\":1024702,\"EQPTYPEDETAIL\":\"SORTING\",\"EQPGROUP\":\"FT-160\",\"MODEL\":\"C3D300\",\"COMCLASS\":\"UP-Time\",\"STATE\":\"Productive-Time\",\"SUBSTATE\":\"RUN\",\"HOLDSTATE\":\"Off\",\"ISBATCH\":\"N\",\"ISMULTIPART\":\"N\",\"STYLE\":0,\"CREATED\":\"2020/05/12 20:02:20\",\"UPDATED\":\"2020/12/11 21:49:05\",\"UPDATEDBY\":\"admin\",\"ISAVAILABLE\":true,\"ISBATCHLOTSIZECONTROL\":false},\"LISTEQUIPMENT\":[{\"EQUIPMENTID\":\"AE0366\",\"STYLE\":0}]}}}";
//        initEdit(etItemEqp, new editTextListener() {
//            @Override
//            public void onTextChangeListener(String s) {
//                BaseResponseBean<EqpInfoEntity> dd = (new Gson()).fromJson(s1, new TypeToken<BaseResponseBean<EqpInfoEntity>>() {
//                }.getType());
//                if (dd.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//                    String objectRRN = dd.getResponse().getBody().getEQUIPMENT().getOBJECTRRN();
//                    if (objectRRN.equals("")){
//                        showToast("未获取到当前测试机主键",false);
//                        etItemEqp.setText("");
//                        etItemEqp.requestFocus();
//                        return;
//                    }
//
//                    String s2 = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"}}}";
//                    BaseResponseBean<EquipmentEntity> d = (new Gson()).fromJson(s2, new TypeToken<BaseResponseBean<EquipmentEntity>>() {
//                    }.getType());
//                    if (d.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//                        if (d.getResponse().getBody() != null){
//                            if (d.getResponse().getBody().getEQUIPMENT().size() > 0) {
//                                if (!d.getResponse().getBody().getEQUIPMENT().get(0).getEQUIPMENTID().equals("")) {
//                                    showToast(s + "测试机已绑定在" + d.getResponse().getBody()
//                                            .getEQUIPMENT().get(0).getEQUIPMENTID() + "分选机上，请解绑后再进行操作！", false);
//                                    etItemEqp.setText("");
//                                    etItemEqp.requestFocus();
//                                    return;
//                                }
//                            }
//                        }
//                        EquipmentEntity entity = new EquipmentEntity();
//                        entity.setOBJECTRRN(objectRRN);
//                        entity.setEQUIPMENTID(s);
//                        mItemList.add(entity);
//                        carrierAdapter.addData(s);
//                        etItemEqp.setText("");
//                        etItemEqp.requestFocus();
//                    }
//                }
//            }
//        });

        initEdit(etItemEqp, s -> {

            if (getText(etEqpWorkID).equals("")){
                showToast("请先扫描分选机",false);
                etItemEqp.setText("");
                etEqpWorkID.requestFocus();
                return;
            }

            if (s.equals(getText(etEqpWorkID))){
                showToast("不能扫入相同设备",false);
                etItemEqp.setText("");
                etItemEqp.requestFocus();
                return;
            }

            if (carrierAdapter.getData().size() > 0){
                showToast("一台分选机只能绑定一台测试机，请先解绑",false);
                etItemEqp.setText("");
                etItemEqp.requestFocus();
                return;
            }


            if (carrierAdapter.getData().contains(s)){
                showToast("当前测试机已在列表中",false);
                etItemEqp.setText("");
                etItemEqp.requestFocus();
                return;
            }

            LotUtils.searchEqpInfo(s, EqpCombinationActivity.this, getSupportFragmentManager(), new LotUtils.netCallback<EqpInfoEntity>() {
                @Override
                public void onSuccess(EqpInfoEntity response) {
                    String objectRRN = response.getEQUIPMENT().getOBJECTRRN();
                    if (objectRRN.equals("")){
                        showToast("未获取到当前测试机主键",false);
                        etItemEqp.setText("");
                        etItemEqp.requestFocus();
                        return;
                    }

                    FreeUI_EntityCallBack<BaseResponseBean<EquipmentEntity>> callBack = new CustomDialogEntityCallBack<BaseResponseBean<EquipmentEntity>>
                            (new TypeToken<BaseResponseBean<EquipmentEntity>>() {
                            }.getType(), getSupportFragmentManager(), this) {

                        @Override
                        public void onSuccess(Response<BaseResponseBean<EquipmentEntity>> response) {
                            super.onSuccess(response);
                            if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                                if (response.body().getResponse().getBody() != null){
                                    if (response.body().getResponse().getBody().getEQUIPMENT().size() > 0) {
                                        if (!response.body().getResponse().getBody().getEQUIPMENT().get(0).getEQUIPMENTID().equals("")) {
                                            showToast(s + "测试机已绑定在" + response.body().getResponse().getBody()
                                                    .getEQUIPMENT().get(0).getEQUIPMENTID() + "分选("+ response.body().getResponse()
                                                    .getBody().getEQUIPMENT().get(0).getLOCATION() + ")机上，请解绑后再进行操作！", false);
                                            etItemEqp.setText("");
                                            etItemEqp.requestFocus();
                                            return;
                                        }
                                    }
                                }
                                EquipmentEntity entity = new EquipmentEntity();
                                entity.setOBJECTRRN(objectRRN);
                                entity.setEQUIPMENTID(s);
                                mItemList.add(entity);
                                carrierAdapter.addData(s);
                                etItemEqp.setText("");
                                etItemEqp.requestFocus();
                            }
                        }

                        @Override
                        public void onError(Response<BaseResponseBean<EquipmentEntity>> response) {
                            super.onError(response);
                            loadError(response.getException(),"EQPQUERY");
                        }
                    };

                    JsonObject map = new JsonObject();
                    map.addProperty("WHERECLASE",s);
                    NetUtils.requestPostNet("CPC.EQPCOMBLNE","EQPCOMBLNE",EqpCombinationActivity.this,map,callBack);


                }

                @Override
                public void onFail(Throwable t) {
                    loadError(t,"EQPQUERY");
                }
            });
        });

        carrierAdapter.setOnRemoveListener(s -> {
            Iterator<EquipmentEntity> iterator = mItemList.iterator();
            while (iterator.hasNext()){
                if (iterator.next().getEQUIPMENTID().equals(s)){
                    iterator.remove();
                }
            }
        });
    }

    private void requestItemRRN(String mainObjectRRN) {
//        String ss = "{\"Response\":{\"Header\":{\"TRANSACTIONID\":\"\",\"RESULT\":\"SUCCESS\"},\"Body\":{\"LISTEQUIPMENT\":[]}}}";
//        BaseResponseBean<EquipmentEntity> dd = (new Gson()).fromJson(ss, new TypeToken<BaseResponseBean<EquipmentEntity>>() {
//        }.getType());
//        if (dd.isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
//            List<EquipmentEntity> listequipment = dd.getResponse().getBody().getLISTEQUIPMENT();
//            if (listequipment.size() > 0){
//                carrierAdapter.getData().clear();
//                mItemEqpList.clear();
//                for (EquipmentEntity entity : listequipment){
//                    carrierAdapter.addData(entity.getEQUIPMENTID());
//                    mItemList.add(entity);
//                    mItemEqpList.add(entity.getEQUIPMENTID());
//                }
//            }
//        }
        FreeUI_EntityCallBack<BaseResponseBean<EquipmentEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EquipmentEntity>>
                (new TypeToken<BaseResponseBean<EquipmentEntity>>() {
                }.getType(), getSupportFragmentManager(), this) {

            @Override
            public void onSuccess(Response<BaseResponseBean<EquipmentEntity>> response) {
                super.onSuccess(response);
                if (response.body().isSuccess(getApplicationContext(),true,getSupportFragmentManager())){
                    List<EquipmentEntity> listequipment = response.body().getResponse().getBody().getLISTEQUIPMENT();
                    carrierAdapter.getData().clear();
                    mItemEqpList.clear();
                    carrierAdapter.notifyDataSetChanged();
                    if (listequipment.size() > 0){
                        for (EquipmentEntity entity : listequipment){
                            carrierAdapter.addData(entity.getEQUIPMENTID());
                            mItemList.add(entity);
                            mItemEqpList.add(entity.getEQUIPMENTID());
                        }
                    }
                }
            }

            @Override
            public void onError(Response<BaseResponseBean<EquipmentEntity>> response) {
                super.onError(response);
                loadError(response.getException(),"EQPCOMBINE");

            }
        };
        JsonObject map = new JsonObject();
        map.addProperty("ACTIONTYPE","SUBEQPCOMBINEQUERY");
        EquipmentEntity equipmentEntity = new EquipmentEntity();
        equipmentEntity.setOBJECTRRN(mainObjectRRN);
        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(equipmentEntity)).getAsJsonObject());
        NetUtils.requestPostNet("MES.EQPCOMBINE","EQPCOMBINE",EqpCombinationActivity.this,map,callBack);
    }

    @Override
    protected void initData() {

    }

    @OnClick({R.id.tvBaseSubmit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tvBaseSubmit:
                if (actionControl("Submit32"))
                    return;

                if (getText(etEqpWorkID).equals("")){
                    showToast("分选机不能为空",false);
                    return;
                }

                if (carrierAdapter.getData().size() > 1){
                    showToast("一台分选机只能绑定一台测试机，请先解绑",false);
                    return;
                }

                StringBuffer sb = new StringBuffer();
                StringBuffer sb1 = new StringBuffer();
                StringBuffer sb2 = new StringBuffer();

                if(carrierAdapter.getData().size() > 0){
                        for (String s : carrierAdapter.getData()){
                            if (mItemEqpList.size() > 0){
                                for (String eqp : mItemEqpList){
                                    if (s.equals(eqp)){
                                        sb.append(s + ",");
                                    }else {
                                        sb1.append(eqp + ";");
                                    }
                                }
                            }
                            sb2.append(s + ";");
                        }

                    if (!sb1.toString().equals("")){
                        showToast(sb1.toString() + "测试机已绑定" + getText(etEqpWorkID) + "分选机，无法再绑定"
                                + sb2.toString() + "测试机，请解绑后再绑定!",false);
                        return;
                    }
                }
                showSubmitDialog(new onSubmitListener() {
                    @Override
                    public void setOnSubmitListener() {
                        FreeUI_EntityCallBack<BaseResponseBean<EquipmentEntity>> callBack = new FreeUI_DialogEntityCallBack<BaseResponseBean<EquipmentEntity>>
                                (new TypeToken<BaseResponseBean<EquipmentEntity>>() {
                                }.getType(), getSupportFragmentManager(), this) {

                            @Override
                            public void onSuccess(Response<BaseResponseBean<EquipmentEntity>> response) {
                                super.onSuccess(response);
                                if (response.body().isSuccess(getApplicationContext(),false,getSupportFragmentManager())){
                                    showConfirmDialog("提交成功");
                                    mItemEqpList.clear();
                                    carrierAdapter.getData().clear();
                                    carrierAdapter.notifyDataSetChanged();
                                    etEqpWorkID.setText("");
                                    etItemEqp.setText("");
                                }
                            }

                            @Override
                            public void onError(Response<BaseResponseBean<EquipmentEntity>> response) {
                                super.onError(response);
                                loadError(response.getException(),"EQPCOMBINE");

                            }
                        };

                        JsonObject map = new JsonObject();
                        map.addProperty("ACTIONTYPE","EQPCOMBINE");
                        EquipmentEntity equipmentEntity = new EquipmentEntity();
                        equipmentEntity.setOBJECTRRN(mMainObjectRRN);
                        map.add("EQUIPMENT",new JsonParser().parse(new Gson().toJson(equipmentEntity)).getAsJsonObject());
                        map.add("EQUIPMENTLIST",new JsonParser().parse(new Gson().toJson(mItemList)).getAsJsonArray());
                        NetUtils.requestPostNet("MES.EQPCOMBINE","EQPCOMBINE",EqpCombinationActivity.this,map,callBack);
                    }
                });
                break;
        }
    }

    public class EquipmentEntity implements Serializable{
        private String OBJECTRRN;
        private String EQUIPMENTID;
        private String LOCATION;
        private List<EquipmentEntity> EQUIPMENT;
        private List<EquipmentEntity> LISTEQUIPMENT;

        public String getLOCATION() {
            return LOCATION == null ? "" : LOCATION;
        }

        public void setLOCATION(String LOCATION) {
            this.LOCATION = LOCATION;
        }

        public String getEQUIPMENTID() {
            return EQUIPMENTID == null ? "" : EQUIPMENTID;
        }

        public void setEQUIPMENTID(String EQUIPMENTID) {
            this.EQUIPMENTID = EQUIPMENTID;
        }

        public List<EquipmentEntity> getLISTEQUIPMENT() {
            if (LISTEQUIPMENT == null) {
                return new ArrayList<>();
            }
            return LISTEQUIPMENT;
        }

        public void setLISTEQUIPMENT(List<EquipmentEntity> LISTEQUIPMENT) {
            this.LISTEQUIPMENT = LISTEQUIPMENT;
        }

        public String getOBJECTRRN() {
            return OBJECTRRN == null ? "" : OBJECTRRN;
        }

        public void setOBJECTRRN(String OBJECTRRN) {
            this.OBJECTRRN = OBJECTRRN;
        }

        public List<EquipmentEntity> getEQUIPMENT() {
            if (EQUIPMENT == null) {
                return new ArrayList<>();
            }
            return EQUIPMENT;
        }

        public void setEQUIPMENT(List<EquipmentEntity> EQUIPMENT) {
            this.EQUIPMENT = EQUIPMENT;
        }
    }

}